const Post = require("../models/post");
const Like = require("../models/like");
const sequelize = require("../config/sequelize");
const messageService = require("./message");

exports.like = async function(authorId,userId,postId){
    const post = await Post.findByPk(postId);
    if(!post){
        throw(new Error("文章已经被删除！"));
    }
    await Like.create({
        userId,postId
    });

    //添加消息,如果是自己点赞自己的文章则不添加消息
   if(userId !== authorId){
        await messageService.add('点赞文章',authorId,userId,0,postId,0);
    }
}

exports.dislike = async function(authorId,userId,postId){
    const post = await Post.findByPk(postId);
    if(!post){
        throw(new Error("文章已经被删除！"));
    }
    await Like.destroy({
        where:{
            userId,
            postId
        },
        individualHooks:true
    });

    //删除点赞消息
    if(userId !== authorId){
        await messageService.delete(userId,postId,0);
    }
}

//删除某篇文章下的所有点赞
exports.deleteAll = async function(postId){
    return Like.destroy({
        where:{postId}
    })
}

//获取当前用户点赞的文章
exports.userLikePost = async function(userId){
    const likePost = await Like.findAll({
        where:{
            userId:userId
        }
    });
    let likeArr = [];
    likePost.forEach(item=>{
        likeArr.push(item.postId);
    });
    return likeArr;
}

//判断当前用户是否点赞该文章
exports.isLikePost = async function(userId,postId){
    const like = await Like.findOne({
        where:{
            userId,postId
        }
    });
    if(like){
        return true;
    }else{
        return false;
    }
}